package com.lyx.moocmusic.login.presenter;


import com.google.gson.Gson;
import com.lyx.lib_network.okhttp.listener.DisposeDataListener;
import com.lyx.moocmusic.api.MockData;
import com.lyx.moocmusic.api.RequestCenter;
import com.lyx.moocmusic.events.LoginEvent;
import com.lyx.moocmusic.login.inter.IUserLoginPresenter;
import com.lyx.moocmusic.login.inter.IUserLoginView;
import com.lyx.moocmusic.login.manager.UserManager;
import com.lyx.moocmusic.model.user.User;

import org.greenrobot.eventbus.EventBus;

/**
 * 登陆页面对应Presenter
 */
public class UserLoginPresenter implements IUserLoginPresenter {

    private IUserLoginView mIView;

    public UserLoginPresenter(IUserLoginView iView) {
        mIView = iView;
    }

    @Override
    public void login(String username, String password) {
        mIView.showLoadingView();
        RequestCenter.login(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mIView.hideLoadingView();
                User user = (User) responseObj;
                UserManager.getInstance().saveUser(user);
                //发送登陆Event
                EventBus.getDefault().post(new LoginEvent());
                mIView.finishActivity();
            }

            @Override
            public void onFailure(Object reasonObj) {
                mIView.hideLoadingView();
                onSuccess(new Gson().fromJson(MockData.LOGIN_DATA, User.class));
                mIView.showLoginFailedView();
            }
        });
    }

}
